package com.dg.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.co.service.IPersonService;
import com.co.dynamic.annotation.DataSource;
import com.co.model.Person;
import com.dg.service.impl.BaseGenericityServiceImpl;
import com.dg.service.impl.BaseObjectServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.system.controller.BaseController;
import com.system.pojo.ParamsData;
import com.system.util.Tools;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("/person")
public class PersonController extends BaseController{
    
	@Resource(name="objectService")
	private BaseObjectServiceImpl objectService;
	
	@Resource(name="genericityService")
	private BaseGenericityServiceImpl genericityService;
	
    private IPersonService personService;
    
    public IPersonService getPersonService() {
        return personService;
    }

    @Autowired
    public void setPersonService(IPersonService personService) {
        this.personService = personService;
    }

    //测试实体类接口1
    @RequestMapping("/showPersonT")
    public String showPersons(Model model) throws Exception{
    	System.out.println("访问到了。。。。。。。。。。showPerson。。。。。。。");
    	ParamsData pd=this.getParamsData();
    	
    	PageHelper.startPage(1, 100);
    	List<Person> persons = personService.loadPersons();
        for (Person p : persons) {
			System.out.println(p.getId()+" -- "+p.getName()+" -- "+p.getAge());
		}
    	
    	// 取分页信息
        PageInfo<Person> page = new PageInfo<Person>(persons);
        long total = page.getTotal(); //获取总记录数
        System.out.println("------总条数：" + total);
        System.out.println(page.getPageNum());
        System.out.println(page.getPageSize());
        System.out.println(page.getStartRow());
        System.out.println(page.getEndRow());
        System.out.println(page.getPages());
        System.out.println(page.getFirstPage());
        System.out.println(page.getLastPage());
        System.out.println(page.isIsFirstPage());
        System.out.println(page.isIsLastPage());
        System.out.println(page.isHasPreviousPage());
        System.out.println(page.isHasNextPage());
        
        pd.put("title", "default");
        pd.put("total", total);
    	
        model.addAttribute("persons", persons);
        model.addAttribute("pd",pd);
        
//        test();
        
        return "showperson";
    }
    
    //测试实体类接口2
    @RequestMapping("/showPersonG")
    @ResponseBody
    public String showPersonG(Model model) {
    	System.out.println("访问到了。。。。。。。。。。showPersonG。。。。。。。");
    	
    	List<Person> list=genericityService.findAll("Person.queryAllGenericity", null);
    	
    	return Tools.toJson(list);
    }
    
    //测试通用接口
    @RequestMapping("/showPersonO")
    public String showPersonO(Model model) {
    	System.out.println("访问到了。。。。。。。。。。showPersonO。。。。。。。");
    	
    	PageHelper.startPage(1, 4);
    	List<ParamsData> list=(List<ParamsData>) objectService.findAll("Person.queryAllObject", null);
    	
    	// 取分页信息
        PageInfo<ParamsData> pageInfo = new PageInfo<ParamsData>(list);
        long total = pageInfo.getTotal(); //获取总记录数
        System.out.println("------总条数：" + total);
    	
    	model.addAttribute("persons", list);
    	model.addAttribute("title","object");
    	model.addAttribute("total",total);
    	
    	return "showpersonO";
    }
    
    //跳转bootstrap-table页面
    @RequestMapping("/showPerson")
    public ModelAndView toView() {
    	mv=this.getModelAndView();
    	mv.setViewName("bootstraptest/showperson");
    	
    	return mv;
    }
    
    //返回bootstrap-table格式数据（返回string格式和json一样）
    @RequestMapping("/getPersonData")
    @DataSource(value="dataSource2")
    @ResponseBody
    public JSONObject getPersonData() {
    	pd=this.getParamsData();
    	int pageNumber=new Integer(pd.getString("pageNumber"));
    	int pageSize=new Integer(pd.getString("pageSize"));
    	
    	PageHelper.startPage(pageNumber,pageSize);
    	List<ParamsData> list=(List<ParamsData>) objectService.findAll("Person.queryAllObject", null);
    	
    	PageInfo<ParamsData> pageInfo=new PageInfo<ParamsData>(list);
    	long total = pageInfo.getTotal(); //获取总记录数
    	System.out.println(Tools.pageJson(list, total));
    	return Tools.pageJson(list,total);
    }
    
    //跳转layer-table页面
    @RequestMapping("/toLayerTable")
    public ModelAndView toLayerTable() {
    	mv=this.getModelAndView();
    	mv.setViewName("layertabletest/showperson");
    	
    	return mv;
    }
    
    //返回layer-table格式数据（返回string格式和json一样）
    @RequestMapping("/getPersonDataL")
    @ResponseBody
    public JSONObject getPersonDataL() {
    	pd=this.getParamsData();
    	int pageNumber=new Integer(pd.getString("page"));
    	int pageSize=new Integer(pd.getString("limit"));
    	
    	PageHelper.startPage(pageNumber,pageSize);
    	List<ParamsData> list=(List<ParamsData>) objectService.findAll("Person.queryAllObject", null);
    	
    	PageInfo<ParamsData> pageInfo=new PageInfo<ParamsData>(list);
    	long total = pageInfo.getTotal(); //获取总记录数
    	JSONObject json=new JSONObject();
    	json.put("code", 0);
    	json.put("msg", "成功");
		json.put("count", total);
		json.put("data", list);
		
		return json;
    	
    }
    
    //调用 http接口，并接受返回数据
    public static void test() throws Exception {
    	String jsonStr = "";
	 	
		System.out.println("执行到了");
		 // 创建HttpClient实例     
		org.apache.http.client.HttpClient httpclient = new DefaultHttpClient();  
        // 创建Get方法实例     
		HttpPost httpgets = new HttpPost("http://192.168.0.100:8080/order114/servlet/rest/waitorder");
        HttpResponse res = httpclient.execute(httpgets);  
        
        HttpEntity entity = res.getEntity();

        if (entity != null) {    
            InputStream instreams = entity.getContent();    
            jsonStr = convertStreamToString(instreams);     
            //System.out.println(jsonStr);  
            httpgets.abort();    
        } 
        System.out.println(jsonStr);
	}
    
    public static String convertStreamToString(InputStream is) throws UnsupportedEncodingException {      
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));      
        StringBuilder sb = new StringBuilder();      
       
        String line = null;      
        try {      
            while ((line = reader.readLine()) != null) {  
                sb.append(line + "\n");      
            }      
        } catch (IOException e) {      
            e.printStackTrace();      
        } finally {      
            try {      
                is.close();      
            } catch (IOException e) {      
               e.printStackTrace();      
            }      
        }      
        return sb.toString();      
    }  
    
    public static void main(String[] args) throws Exception {
		
    	test();
    	
	}
    
}